package com.guo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guo.common.BaseResponse;
import com.guo.common.ErrorCode;
import com.guo.common.ResultUtils;
import com.guo.exception.BusinessException;
import com.guo.model.domain.User;
import com.guo.model.request.UserLoginRequest;
import com.guo.model.request.UserRegisterRequest;
import com.guo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.guo.constant.UserConstant.ADMIN_ROLE;
import static com.guo.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        String checkPassword = request.getCheckPassword();
        String planetCode=request.getPlanetCode();
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        long userId = userService.userRegister(userAccount,userPassword,checkPassword,planetCode);
        return ResultUtils.success(userId);
    }

    @PostMapping("/login")
    public BaseResponse<User> doLogin(@RequestBody UserLoginRequest request,
                        HttpServletRequest httpServletRequest){
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.doLogin(userAccount, userPassword, httpServletRequest);
        return ResultUtils.success(user);
    }

    @GetMapping("/search")
    public BaseResponse searchUser(String username, HttpServletRequest request){
       if(!isAdmin(request)){
           return ResultUtils.error(ErrorCode.NO_AUTH);
       }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(username)){
            userQueryWrapper.like("username",username);
        }
        List<User> list = userService.list(userQueryWrapper);
        List<User> resultList = list.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(resultList);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(long id, HttpServletRequest request){
        if (!isAdmin(request)){
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        if(id<=0){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        boolean flag = userService.removeById(id);
        return ResultUtils.success(flag);
        }

    @PostMapping("/logout")
    public BaseResponse<Integer> logout(HttpServletRequest request){
       if(request ==null){
           return ResultUtils.error(ErrorCode.PARAMS_ERROR);
       }
        int id = userService.userLogout(request);
        return ResultUtils.success(id);
   }
   @GetMapping("/current")
   public BaseResponse<User> current(HttpServletRequest request){
       User currentUser = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
       if(currentUser==null){
           return ResultUtils.error(ErrorCode.NOT_LOGIN);
       }
       User user = userService.getById(currentUser.getId());
       User safetyUser = userService.getSafetyUser(user);
       return ResultUtils.success(safetyUser);
   }

    /**
     * 判断是否为管理员
     * @param request
     * @return
     */
 private boolean isAdmin(HttpServletRequest request){
     Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
     User user=(User) userObject;
     if(user ==null && user.getUserRole()!=ADMIN_ROLE){
         return false;
     }
     return true;
  }

}
